from fastapi import APIRouter, Request, Depends

from applications.configs.func import render_template
from applications.configs.response import ResponseMessage
from applications.models import Session, get_session
from applications.models.users import Users
from applications.schemas.Power import AddPowerSchemas
from applications.schemas.Users import UserUpdateShow, UserLogin
from applications.services.power import power_add_action, get_power_list, get_users_list, user_update_update, \
    user_delete_action, power_delete_action

power_router = APIRouter(prefix="/power", tags=["权限管理"])


# 获取菜单
@power_router.get("/", summary="用户列表", description="用户列表")
def user_list_html(request: Request):
    return render_template(request, "/power/user.html", {"users": get_users_list()})


@power_router.get("/list", summary="权限列表", description="权限列表")
def power_list_html(request: Request):
    return render_template(request, "/power/index.html", {"powers": get_power_list()})


@power_router.get("/add", summary="添加权限页面", description="添加权限页面")
def add_power_html(request: Request):
    return render_template(request, "/power/add.html", {"powers": get_power_list()})


@power_router.post("/add", summary="添加权限", description="添加权限")
def add_power_func(data: AddPowerSchemas):
    code, data = power_add_action(data)
    return ResponseMessage(code, data)


@power_router.get("/userUpdate", summary="修改用户信息", description="修改用户信息")
def user_update_html(request: Request, id: int, session: Session = Depends(get_session)):
    status = 0
    user_param = None
    if id > 0:
        user_param = session.query(Users).filter(Users.id == id).first()
        status = 1 if user_param.status == 1 else 0
    return render_template(request, "/power/user_update.html", {"id": id, "status": status, "powers": get_power_list(user_param)})


@power_router.post("/userUpdate", summary="修改用户信息", description="修改用户信息")
def user_update_func(data: UserUpdateShow):
    code, data = user_update_update(data)
    return ResponseMessage(code, data)


@power_router.post("/delete", summary="删除用户", description="删除用户")
def user_delete_func(data: UserLogin):
    code, data = user_delete_action(data)
    return ResponseMessage(code, data)


@power_router.post("/delete_power", summary="删除权限", description="删除权限")
def power_delete_func(data: UserLogin):
    code, data = power_delete_action(data)
    return ResponseMessage(code, data)